﻿using System;
using System.Windows;
using SABnzbdNET.Events;
using SABnzbdNET.ViewModels;

namespace SABnzbdNET.Views
{
    /// <summary>
    /// Interaction logic for MainView.xaml
    /// </summary>
    public partial class MainView : Window
    {
        private readonly IEventAggregator eventAggregator;

        public MainView()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
            eventAggregator = EventAggregatorProvider.Instance;
            eventAggregator.Subscribe<SetNotifyIconVisibilityMessage>(message => SetNotifyIconVisibility(message.Visibility));
            eventAggregator.Subscribe<ShowTrayBallonMessage>(message => ShowBalloon(message.Title, message.Text, message.Icon));
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            ((MainViewModel)DataContext).HandleLoadedEvent();
        }

        private void OnStateChanged(object sender, EventArgs args)
        {
            ((MainViewModel)DataContext).HandleStateChangedEvent();
        }

        private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            ((MainViewModel)DataContext).HandleIsVisibleChangedEvent();
        }

        private void ShowBalloon(string title, string message, Hardcodet.Wpf.TaskbarNotification.BalloonIcon icon)
        {
            if (NotifyIcon.Visibility == Visibility.Visible)
                NotifyIcon.ShowBalloonTip(title, message, icon);
        }

        private void SetNotifyIconVisibility(Visibility visibility)
        {
            NotifyIcon.Visibility = visibility;

            var context = ((MainViewModel)DataContext);
            if (!Application.Current.Windows[0].IsVisible && visibility == Visibility.Visible && !context.HasBeenNotifiedOfMinimized)
            {
                NotifyIcon.ShowBalloonTip("SABnzbdNET minimimzed"
                    , "SABnzbdNET has been minimized to tray.\nDouble-click or right-click icon to restore."
                    , Hardcodet.Wpf.TaskbarNotification.BalloonIcon.Info);
                context.HasBeenNotifiedOfMinimized = true;
            }
        }
    }
}
